from rest_framework_simplejwt.settings import api_settings
from rest_framework_simplejwt.tokens import RefreshToken

class CustomRefreshToken(RefreshToken):
    '''
    重写 RefreshToken 类自定义令牌
    '''
    @classmethod
    def for_user(cls, user):
        # 调用父类方法生成默认的 Token
        token = super().for_user(user)
        # 动态获取 USER_ID_CLAIM 和 USER_ID_FIELD
        user_id_claim = api_settings.USER_ID_CLAIM
        user_id_field = api_settings.USER_ID_FIELD
        # 获取用户 ID
        user_id = getattr(user, user_id_field)
        # 因为用户id很长前端会失去精度，所以这里只返回字符串形式
        token[user_id_claim] = str(user_id)
        return token
    
